/**
 *@Description 清单详情页
 *@Author zhangnf
 *@Date 2015-09-25
 */
var billDetailCtrl  = new XFApp.client();
XFApp.client.prototype.billDetail = {
	successCode : "10000",
	page : null,
	urlItems : {
		getBillByIdURL : basePath+"/userCenter/bill/getBillById",
		saveBillURL : basePath+"/userCenter/bill/saveBill",
		queryByPageURL : basePath+"/userCenter/bill/getDetailPage",
		delDetailURL : basePath+"/userCenter/bill/delDetail",
		saveDetailURL : basePath+"/userCenter/bill/saveDetail",
		getDetailByIdURL : basePath+"/userCenter/bill/getDetailById",
		applyURL : basePath+"/userCenter/bill/apply",
	},
	initData : function(billId){
		_this = this;
		$.ajax( {  
		    url:_this.urlItems.getBillByIdURL,
		    data:{  
		             id : billId
		    },  
		    type:'post',  
		    cache:false,  
		    dataType:'json',  
		    success:function(data) {
		    	if(data.code !=_this.successCode
		    			|| null == data.result){
	        		return;
	        	}
		    	var bill = data.result;
		    	
		    	$("#editForm #detailTitle").text(_this.titleDisplay($("#typeId").val()));
		    	
		    	$("#editForm #billCode").text(bill.billCode);
		    	$("#editForm #docketStatus").text(dksCtrl.dockerstatus.get(bill.docketStatus));
		    	$("#editForm #customerCode").text(bill.customerCode);
		    	$("#editForm #customerName").text(bill.customerName);
		    	$("#editForm #orderCode").text(bill.orderCode);
		    	$("#editForm #transCode").text(bill.transCode);
		    	$("#editForm #customsCode").text(bill.customsCode);
		    	$("#editForm #applyTime").text(_this.dataFormat(bill.applyTime));
		    	$("#editForm #ebpCode").text(bill.ebpCode);
		    	$("#editForm #ebpName").text(bill.ebpName);
		    	$("#editForm #logisticsCode").text(bill.logisticsCode);
		    	$("#editForm #logisticsName").text(bill.logisticsName);
		    	$("#editForm #logisticsNo").text(bill.logisticsNo);
		    	$("#editForm #billOrderNo").text(bill.billOrderNo);
		    	$("#editForm #portCode").text(bill.portCode);
		    	$("#editForm #ieDate").text(_this.dataFormat(bill.ieDate));
		    	$("#editForm #ownerCode").text(bill.ownerCode);
		    	$("#editForm #ownerName").text(bill.ownerName);
		    	$("#editForm #tradeCode").text(bill.tradeCode);
		    	$("#editForm #tradeName").text(bill.tradeName);
		    	$("#editForm #agentCode").text(bill.agentCode);
		    	$("#editForm #agentName").text(bill.agentName);
		    	$("#editForm #trafName").text(bill.trafName);
		    	$("#editForm #voyageNo").text(bill.voyageNo);
		    	$("#editForm #billNo").text(bill.billNo);
		    	$("#editForm #loctNo").text(bill.loctNo);
		    	$("#editForm #licenseNo").text(bill.licenseNo);
		    	$("#editForm #country").text(bill.country);
		    	$("#editForm #freight").text(billDetailCtrl.fmoney(bill.freight));
		    	$("#editForm #freightCurr").text(bill.freightCurr);
		    	$("#editForm #insureFee").text(billDetailCtrl.fmoney(bill.insureFee));
		    	$("#editForm #insurefeeCurr").text(bill.insurefeeCurr);
		    	$("#editForm #packNo").text(bill.packNo);
		    	$("#editForm #grossWeight").text(bill.grossWeight);
		    	$("#editForm #netWeight").text(bill.netWeight);
		    	
		    	$("#editForm #loctNo").val(bill.loctNo);
		    	$("#editForm #licenseNo").val(bill.licenseNo);
		    	$("#editForm #remark").val(bill.remark);
		    	
		    	$("#editForm #trademodeHidden").val(bill.tradeMode);
		    	$("#editForm #destinationportHidden").val(bill.destinationPort);
		    	$("#editForm #wrapTypeHidden").val(bill.wrapType);
		    	$("#editForm #transferModeHidden").val(bill.trafMode);
		    	$("#editForm #freightMarkHidden").val(bill.freightMark);
		    	$("#editForm #insurefeeMarkHidden").val(bill.insurefeeMark);
		    			    	
		    	//贸易方式
		    	dictCtrl.dictionary.load("trademode","trademodeHidden");
		    	//指运港
		    	dictCtrl.dictionary.load("destinationport","destinationportHidden");
		    	//包装种类
		    	dictCtrl.dictionary.load("wrapType","wrapTypeHidden");
		    	//运输方式
		    	dictCtrl.dictionary.load("transferMode","transferModeHidden","trafMode");
		    	//运费标志
		    	dictCtrl.dictionary.load("feeMark","freightMarkHidden","freightMark");
		    	//保费标志
		    	dictCtrl.dictionary.load("feeMark","insurefeeMarkHidden","insurefeeMark");
		    	
		     },  
		     error : function() {  
		    	 window.webDialogUtil.alert("提示","操作失败");
		     }  
		});
	},
	titleDisplay : function(typeId){
		switch(typeId){
			case 0:return "查看";
			case 1:return "修改";
			case 2:return "新增";
			default : return "";
		}
	},
	saveForm : function(){
		_this = this;
		$.ajax( {  
		    url:_this.urlItems.saveBillURL,
		    data:$('#editForm').serialize(),  
		    type:'post',  
		    cache:false,  
		    dataType:'json',  
		    success:function(data) {
		    	window.webDialogUtil.alert("提示",data.msg);
		     },  
		     error : function() {  
		    	 window.webDialogUtil.alert("提示","操作失败");
		     }  
		});
	},
	applyForm : function(){
		_this = this;
		$.ajax( {  
		    url:_this.urlItems.applyURL,
		    data:$('#editForm').serialize(),  
		    type:'post',  
		    cache:false,  
		    dataType:'json',  
		    success:function(data) {
		    	window.webDialogUtil.alert("提示",data.msg);
		    	if(data.isSuccess){
		    		_this.refreshOrderId(data.result);
		    	}
		     },  
		     error : function() {
		    	 window.webDialogUtil.alert("提示","操作失败");
		     }  
		});
	},
	refreshOrderId : function(bill){
		if(null == bill){
			return;
		}
		$("#editForm #docketStatus").text(dksCtrl.dockerstatus.get(bill.docketStatus));
	},
	detailPage : function(){
		_this = this;
		var params = $("#editGoodsForm").serialize();
		if(!!_this.page){
			_this.page.page("remote",0,params);
		}else{
			_this.page = $("#page").page({
				pageSize : 10,
				remote: {
					url: _this.urlItems.queryByPageURL,
			        params: params,
			        success: function (data, pageIndex) {
			        	if(data.isSuccess == true){
			        		var pageResult = data.result;
			        		if(null == data 
									|| null == data.result 
										|| null == data.result.itemList
											|| data.result.itemList.length < 1){
			        			$("#page_grid").html('<tr><td align="center" colspan="12">暂无数据</td></tr>');
			        		}else{
			        			$("#page_grid").html($("#dataTmp").render(pageResult.itemList));
			        		}
			        	}else{
			        		webAlert({
					              title:'提示',
					              content:'操作失败!',
					              opacity:.5,
					              bg:"gray",
					              width:300,
					              height:10,
					              button:[
					                      {
					                      name:"关闭",
					                      callback:function(){
					                    	  this.close();
					                      }
					                      }]
					              });
			        	}
			        },
			        error : function(){
			        	window.webDialogUtil.alert("提示","操作失败");
			        }
				},
				firstBtnText : '首页',
				lastBtnText : '尾页',
				prevBtnText : '上一页',
				nextBtnText : '下一页',
				showInfo : true,
				showJump : true,
				jumpBtnText : '跳转',
				showPageSizes : true,
				infoFormat : '共{pageCount}页,{total}项'
			});
		}
	},
	delDetailDialog : function(id,itemName){
		_this = this;
		webAlert({
            title:'提示',
            content:'确定要删除 '+itemName+' 吗?',
            opacity:.5,
            bg:"gray",
            width:300,
            height:10,
            button:[
                    {
                    name:"确定",
                    callback:function(){
                    	_this.delDetail(id);
                    	this.close();
                    }
                    },{
                    name:"取消",
                    callback:function(){
                  	  this.close();
                    }
                    }]
            });
	},
	delDetail : function(id){
		_this = this;
		$.ajax({
		    url:_this.urlItems.delDetailURL,
		    data:{id:id},  
		    type:'post',  
		    cache:false,  
		    dataType:'json',  
		    success:function(data) {
		    	if(true == data.isSuccess){
		    		_this.detailPage();
		    	}
		    	webAlert({
		              title:'提示',
		              content:data.msg,
		              opacity:.5,
		              bg:"gray",
		              width:300,
		              height:10,
		              button:[
		                      {
		                      name:"关闭",
		                      callback:function(){
		                    	  this.close();
		                      }
		                      }]
		              });
		     },  
		     error : function() {
		    	 window.webDialogUtil.alert("提示","操作失败");
		     }  
		});
	},
	initDetailSelect : function(){
		//最终目的国（地区）代码下拉框
    	dictCtrl.dictionary.load("nation","nationHidden");
		//币制下拉框
    	dictCtrl.dictionary.load("currency","editGoodsForm #currencyHidden","editGoodsForm #currency");
    	//计量单位下拉框
    	dictCtrl.dictionary.load("measureUnit","editGoodsForm #unitHidden","editGoodsForm #unit");
    	//法定计量单位下拉框
    	dictCtrl.dictionary.load("measureUnit","editGoodsForm #unit1Hidden","editGoodsForm #unit1");
    	//第二计量单位下拉框
    	dictCtrl.dictionary.load("measureUnit","editGoodsForm #unit2Hidden","editGoodsForm #unit2");
	},
	detailView : function(id,typeId){
		_this = this;
		if(null == id){
			this.initDetailSelect();
			return this.detailDialog(null,typeId);
		}
		$.ajax({
		    url:_this.urlItems.getDetailByIdURL,
		    data:{detailId:id},  
		    type:'post',  
		    cache:false,  
		    dataType:'json',  
		    success:function(data) {
		    	if(false == data.isSuccess){
		    		alert("获取数据失败");
		    		return;
		    	}
		    	_this.detailDialog(data.result,typeId);
		     },  
		     error : function() {
		    	 window.webDialogUtil.alert("提示","操作失败");
		     }  
		});
	},
	detailDialog : function(data,typeId){
		if(null != data){
			$("#editGoodsForm #detailId").val(data.id);
	    	$("#editGoodsForm #updateTime").text(this.dataFormat(data.updateTime));
	    	$("#editGoodsForm #updatePerson").text(data.updatePerson);
	    	
	    	$("#editGoodsForm #itemNo").val(data.itemNo);
	    	$("#editGoodsForm #gNo").val(data.gNo);
	    	$("#editGoodsForm #gCode").val(data.gCode);
	    	$("#editGoodsForm #gName").val(data.gName);
	    	$("#editGoodsForm #gModel").val(data.gModel);
	    	$("#editGoodsForm #barCode").val(data.barCode);
	    	$("#editGoodsForm #goodsCode").val(data.goodsCode);
	    	$("#editGoodsForm #qty").val(data.qty);
	    	$("#editGoodsForm #qty1").val(data.qty1);
	    	$("#editGoodsForm #qty2").val(data.qty2);
	    	$("#editGoodsForm #price").val(data.price);
	    	$("#editGoodsForm #total").val(data.total);
	    	
	    	$("#editGoodsForm #nationHidden").val(data.country);
	    	$("#editGoodsForm #currencyHidden").val(data.currency);
	    	$("#editGoodsForm #unitHidden").val(data.unit);
	    	$("#editGoodsForm #unit1Hidden").val(data.unit1);
	    	$("#editGoodsForm #unit2Hidden").val(data.unit2);
		}else{
	    	$("#editGoodsForm #updateTime").text("");
	    	$("#editGoodsForm #updatePerson").text("");
	    	
			$("#editGoodsForm")[0].reset();
		}
		$("#editGoodsForm #billId").val($("#editForm #billId").val());
		this.initDetailSelect();
		
		webAlert({
            title:billDetailCtrl.billDetail.titleDisplay(typeId),
            content:document.getElementById("goodsView"),
            button:[
					{
					name:"暂存",
					callback:function(){
						if($("#editGoodsForm").validate().form()){
							billDetailCtrl.billDetail.saveGoodsForm();
						}else{
							return false;
						}
					}},
                    {
                    name:"关闭",
                    callback:function(){
                  	  this.close();
                    }
                   }]
            });
	},
	goodsFormValidate : function(){
		$("#editGoodsForm").validate({
	        rules: {
	        	itemNo: "required",
	        	qty: "positiveInteger",
	        	qty1: "positiveInteger",
	        	qty2: "positiveInteger",
	        	price: "amount",
	        	total: "amount"
			  },
			 messages: {
				itemNo: "请填写商品企业编号"
			  }
	    });
		$("#editGoodsForm").validate();
	},
	saveGoodsForm : function(){
		_this = this;
		$.ajax( {
		    url:_this.urlItems.saveDetailURL,
		    data:$('#editGoodsForm').serialize(),  
		    type:'post',  
		    cache:false,  
		    dataType:'json',  
		    success:function(data) {
		    	if(true == data.isSuccess){
		    		_this.detailPage();
		    	}
		    	window.webDialogUtil.alert("提示",data.msg);
		     },  
		     error : function() {
		    	 window.webDialogUtil.alert("提示","操作失败");
		     }  
		});
	},
	dataFormat : function(timeLong){
		if(null == timeLong
				|| "" == timeLong){
			return "";
		}
		return new Date(timeLong*1000).format("yyyy-MM-dd hh:mm:ss")
	},
	event : function(){
		_this = this;
		
		$("#applyBtn").on("click",function(){
			billDetailCtrl.billDetail.applyForm();
		});
		
		$("#saveBtn").on("click",function(){
			billDetailCtrl.billDetail.saveForm();
		});
		
		//商品表单验证
		this.goodsFormValidate();
		//详情分页
    	_this.detailPage();
	},
};
$.views.converters({
	ftime : function(value) {
		return billDetailCtrl.billDetail.dataFormat(value) ;
	},
	fdkstatus : function(value){
		return dksCtrl.dockerstatus.get(value);
	},
	fmoney : function(value){
		if(null == value
				|| "" == value){
			return "";
		}
		return billDetailCtrl.fmoney(value);
	}
});
$.views.helpers({
    "checkStatus": function(status){
    	return $("#editForm #docketStatus").val()==status?true:false;
    }
});
$(function(){
	//初始化编辑数据
	var billId = $("#billId").val();
	if(null != billId && billId > 0){
		billDetailCtrl.billDetail.initData(billId);
	}else{
		//进出口下拉框
    	dictCtrl.dictionary.load("impExp","impExpHidden");
    	//币制下拉框
    	dictCtrl.dictionary.load("currency","currencyHidden");
    	//国家下拉框
    	dictCtrl.dictionary.load("nation","nationHidden");
	}
	
	//初始化事件
	billDetailCtrl.billDetail.event();
});